package com.trade.service.impl;

import java.util.List;

import com.trade.dao.IReposityDao;
import com.trade.exception.BusinessException;
import com.trade.exception.PersistenceException;
import com.trade.model.Reposity;
import com.trade.service.IReposityService;

/**
 * @author Lin Yang
 * 
 */
public class ReposityServiceImpl implements IReposityService {
    private IReposityDao reposityDao;

    public List<Reposity> getAllReposity() throws BusinessException {
        try {
            return reposityDao.getAllReposity();
        } catch (PersistenceException e) {
            throw new BusinessException(e);
        }
    }

    public void save(Reposity reposity) throws BusinessException {
        reposityDao.save(reposity);
    }

    public void setReposityDao(IReposityDao reposityDao) {
        this.reposityDao = reposityDao;
    }

    @Override
    public List<Reposity> getReposityByLogistic(String logisticNumber) throws BusinessException {
        try {
            return reposityDao.getReposityByLogistic(logisticNumber);
        } catch (PersistenceException e) {
            throw new BusinessException(e);
        }
    }

	@Override
	public boolean keeperGetGoods(Long goodsid, Integer goodsnum) {
		List<Reposity> resposities = this.reposityDao.find("from Reposity where goodsId = " + goodsid);
		if (resposities != null) {
			int total = 0;
			for (Reposity r : resposities) total += r.getPurchaseNumber();
			if (goodsnum <= total) {
				for (Reposity r : resposities) {
					int hasNum = r.getPurchaseNumber() - r.getOutNum();
					if (hasNum >= goodsnum) {
						r.setOutNum(goodsnum);
						this.reposityDao.save(r);
						return true;
					} else {
						r.setOutNum(r.getPurchaseNumber());
						this.reposityDao.save(r);
						goodsnum = goodsnum - r.getPurchaseNumber();
					}
				}
			}
		}
		return false;
	}

}
